import config from '@/common/config.js'
import store from '@/store/index.js'
import $http from '@/api/request.js'
import common from '@/common/common.js'

const pop = {


	Toast(msg, state = 1, url) {
		if (state == 1) {
			uni.showToast({
				title: msg,
				icon: 'none',
			})
		} else if (state == 2) {
			uni.showToast({
				title: msg,
				mask: true,
				icon: 'none',
				success: () => {
					setTimeout(() => {
						uni.navigateBack({
							delta: 1
						})
					}, 800)

				}
			})
		} else if (state == 3) {
			uni.showToast({
				title: msg,
				mask: true,
				icon: 'none',
				success: () => {
					setTimeout(() => {
						uni.redirectTo({
							url: url
						})
					}, 800)

				}
			})
		} else if (state == 4) {
			uni.showToast({
				title: msg,
				icon: 'none',
				mask: true,
				duration: 2000
			})
		} else if (state == 5) {
			uni.showToast({
				title: msg,
				icon: 'none',
				mask: true,
				duration: 3000
			})
		}
	},

	showLoading(msg) {
		uni.showLoading({
			title: msg,
			mask: true,
		})
	},
	hideLoading() {
		uni.hideLoading();
	},

	model(title, content = '') {
		return new Promise((resolve, reject) => {
			uni.showModal({
				title,
				content,
				cancelColor: '#cccccc',
				confirmColor: store.state.color,
				success(res) {
					resolve(res.confirm)
				},
				fail(err) {
					reject(err)
				}
			})
		})
	},
	models(title, content, cancelText, confirmText = '确定') {
		return new Promise((resolve, reject) => {
			uni.showModal({
				title,
				content,
				cancelText,
				confirmText,
				cancelColor: '#cccccc',
				confirmColor: store.state.color,
				success(res) {
					resolve(res.confirm)
				},
				fail(err) {
					reject(err)
				}
			})
		})
	},
	imgUrls(imgs) {
		const reg = /^(http|https)/;
		if (!imgs) return;
		if (imgs.search(reg) != -1) return imgs;
		return config.imgUrl + imgs
	},

	staticImg(imgs) {
		return config.staticImg + imgs
	},
	online(imgs) {
		return config.online + imgs
	},
	navBack() {
		setTimeout(() => {
			uni.navigateBack({
				delta: 1
			})
		}, 600)
	},

	getViewInfo(selector) {
		const query = uni.createSelectorQuery().in(this);
		return new Promise((resolve) => {
			query.select(selector).boundingClientRect(data => {
				resolve(data)
			}).exec();
		})
	},

	pageRela(url) {
		uni.reLaunch({
			url
		})
	},

	tabbar() {
		uni.reLaunch({
			url: '/pages/tabbar/tabbar'
		})
	},

	pageScrollTo(scrollTop = 0, duration = 0) {
		uni.pageScrollTo({
			scrollTop,
			duration
		})
	},

	setClip(text) {
		if (!text) return;
		uni.setClipboardData({
			data: text,
			success() {
				pop.Toast('复制成功')
			},
			fail() {
				pop.Toast('复制失败')
			}
		})
	},
	openLocation(item) {
		uni.openLocation({
			latitude: Number.parseFloat(item.s_latitude),
			longitude: Number.parseFloat(item.s_longitude),
			name: item.name,
			address: item.nameAdress,
			success() {
				console.log('打开成功');
			},
			fail(err) {
				console.log(err);
				uni.showToast({
					title: "打开失败!",
					icon: 'none',
				})
			}
		})
	},

	bannelPage(type, url, list_id) {
		if (type == 1) return this.toUrl(`/essay/detailPage?website_list_id=${list_id}`)
		if (type == 2) return this.toUrl(`/essay/ess?website_list_id=${list_id}`)
		if (type == 7 && url) return this.toUrl(url)
	},

	//  自定义跳转路径
	PageUrl(item) {
		if (!item.type) return;
		let id = item.classify_id || item.id;
		if (item.type == 2) { // 商品详情
			this.toUrl(`/pages/Details/Details?goods_id=${id}`)
		}
		if (item.type == 3) { // 商品分类
			this.toUrl(`/pages/dress/dress?classId=${id}`)
		}
		if (item.type == 4) { // 文章栏目
			if (item.website_list_type == 1) { // 单页 详情页
				this.toUrl(`/essay/detailPage?website_list_id=${id}`)
			}
			if (item.website_list_type == 2) { // 文章列表 
				this.toUrl(`/essay/ess?website_list_id=${id}`)
			}
			if (item.website_list_type == 7) { // 路转路由
				this.toUrl(item.website_list_url)
			}
		}
		if (item.type == 5) { // 文章详情页
			this.toUrl(`/essay/detail?website_article_id=${id}`)
		}
		if (item.type == 8) { // 路由
			this.toUrl(item.website_list_url)
		}
		if (item.type == 12) { // 客服
			this.toUrl(`/user/contact`)
		}
		if (item.type == 15) { // 视频号
			if (item.website_list_type == 13) { // 视频号首页
				wx.openChannelsUserProfile({
					finderUserName: item.finderUserName,
				})
			}
			if (item.website_list_type == 14) { // 视频号视频
				wx.openChannelsActivity({
					finderUserName: item.finderUserName,
					feedId: item.feedId
				})
			}
			if (item.website_list_type == 15) { // 视频号直播
				wx.openChannelsLive({
					finderUserName: item.finderUserName
				})
			}
			if (item.website_list_type == 16) { // 视频号活动页
				wx.openChannelsEvent({
					finderUserName: item.finderUserName,
					eventId: item.eventId
				})
			}
		}
		if (item.type == 16) { // 打电话
			uni.makePhoneCall({
				phoneNumber: item.website_list_url
			})
		}
		if (item.type == 17) { // 导航
			uni.openLocation({
				latitude: Number.parseFloat(item.seatData.lat),
				longitude: Number.parseFloat(item.seatData.lng),
				address: item.website_list_url,
				success(res) {
					console.log('打开成功');
				},
				fail(err) {
					console.log(err);
				}
			})
		}
		if (item.type == 18) { // 调查问卷
			wx.openEmbeddedMiniProgram({
				appId: item.appID,
				path: item.website_list_url,
			});
		}


	},

	funcBtnClick(item) {
		if (!store.state.vid) return store.commit('setHome', { showMode: true })
		if (item.funcType == 1) { // 扫码
			uni.scanCode({
				success(res) {
					console.log(res)
					if (res.scanType == 'WX_CODE') { // 小程序太阳码
						let path = decodeURIComponent(res.path)
						common.toUrl('/' + path.replace('scene=p', 'pageType'))

					} else if (res.scanType == 'QR_CODE') { // 二维码
						// 门店余额消费
						if (res.result) common.toUrl(`/moneyPage/pay/playCode?id=${res.result}`)
					}
				},
				fail(err) {
					console.log(err)
				}
			})
		}
	},

	switchTab(item) {
		if (item.path == '/pages/classify/repast' && item.way == 1 && !store.state.vid) return store.commit(
			'setHome', {
				showMode: true
			})
		if (item.path == '/pages/classify/repast') return common.rectTo(`${item.path}?way=${item.way}`)
		if (item.path == '/pages/goods/goods_list') return common.toUrl(`${item.path}?classId=${item.classId}`)
		if (item.path == '/pages/classify/classify' && item.cateType) return common.toUrl(
			`${item.path}?cateType=${item.cateType}`)
		common.rectTo(item.path)
	},

	banerGo(item) {
		/**
		 *  banner 点击跳转  
		 *  type：0不跳转  1跳活动  2跳商品  3跳商品分类  4跳文章栏目  5跳文章详情  6跳表单  7游戏  8跳路由
		 *  goodsType：1 特价  2 团购
		 *  goodsCount：1 单商品 大与1：多商品
		 * **/
		console.log(item, 'item');
		if (item.isTab == 2) return pop.funcBtnClick(item)
		if (item.isTab == 1) return pop.switchTab(item);

		const id = item.id || item.classify_id
		if (!item.type || item.type == 0) return;
		if (item.type == 1) return common.toUrl('/activityPage/seckill/index?act_id=' + id) // 活动
		if (item.type == 2) return common.toGoods(id) // 商品详情
		if (item.type == 3) return common.toUrl("/pages/goods/goods_list?classId=" + id) // 商品分类
		if (item.type == 4) return common.toUrl('/pages/artList/artList?listId=' + id) // 文章栏目
		if (item.type == 5) return common.toUrl('/otherPage/article/artDetail?artId=' + id) // 文章详情
		if (item.type == 6 && id) return common.toUrl('/pages/reserve/formSubmit?ordId=' + id) // 表单
		if (item.type == 6 && !id) return common.toUrl('/pages/reserve/reserve')
		if (item.type == 8) return common.toUrl(item.website_list_url); // 跳本地路由
		if (item.type == 9) return common.toUrl('/userPage/onlineService/webHttp?isURL=' + item
			.website_list_url) // 跳三方url
		if (item.type == 23) return common.toUrl('/otherPage/custom/placeOrder') // 扫码点餐
		if (item.type == 24) return common.toUrl('/otherPage/custom/index?id=' + id) // 自定义内页
		if (item.type == 25 && id) return common.toUrl('/activityPage/bargain/activeList?act_id=' + id) // 砍价活动
		if (item.type == 12) return store.commit('setHomeKefu', {
			showKefu: true
		}) // 客服
		if (item.type == 13 && !store.state.vid) return store.commit('setHome', {
			showMode: true
		})
		if (item.type == 13 && store.state.vid) return store.commit('setHomeShare', {
			showShareQr: true
		}) // 分享首页海报图
		if (item.type == 14) {
			if (item.id) return common.toUrl('/otherPage/forum/theme?classifyid=' + item.id) // 好友圈子
			common.toUrl('/otherPage/forum/forum') // 论坛首页
		}
		if (item.type == 15) { //去视频号
			if (item.website_list_type == 13) { // 主页
				wx.openChannelsUserProfile({
					finderUserName: item.finderUserName,
					complete(res) {
						console.log('去视频号', res)
					}
				})
			}
			if (item.website_list_type == 14) { // 视频
				wx.openChannelsActivity({
					finderUserName: item.finderUserName,
					feedId: item.feedId
				})
			}
			if (item.website_list_type == 15) { // 直播
				wx.openChannelsLive({
					finderUserName: item.finderUserName
				})
			}
			if (item.website_list_type == 16) { // 活动
				wx.openChannelsEvent({
					finderUserName: item.finderUserName,
					eventId: item.eventId
				})
			}
		}
		if (item.type == 16) { // 拨打电话
			uni.makePhoneCall({
				phoneNumber: item.website_list_url
			})
		}
		if (item.type == 17) { // 地址导航
			uni.openLocation({
				latitude: parseFloat(item.seatData.lat),
				longitude: parseFloat(item.seatData.lng),
				complete(res) {
					console.log('地址导航', res)
				}
			})
		}
		if (item.type == 18) { // 腾讯问卷半屏小程序
			wx.openEmbeddedMiniProgram({
				appId: item.appID,
				path: item.path || item.website_list_url
			})
		}
		if (item.type == 22) { // 跳小程序
			wx.navigateToMiniProgram({
				appId: item.website_list_show,
				path: item.website_list_url,
				complete(res) {
					console.log(res)
				}
			})
		}
		if (item.type == 7) { // 跳游戏
			if (!item.actTpl) {
				uni.showToast({
					title: '暂未配置类型哦',
					icon: 'none'
				})
			}
			if (item.actTpl == 'default') {
				//摇一摇
				common.toUrl("/otherPage/lottery/shark?cid=" + id)

			} else if (item.actTpl == 'marquee') {
				//跑马灯
				common.toUrl("/otherPage/lottery/good_luck?cid=" + id)

			} else if (item.actTpl == 'slotMachine') {
				//老虎机
				common.toUrl("/otherPage/lottery/tiger?cid=" + id)

			} else if (item.actTpl == 'bigWheel') {
				//大转盘
				common.toUrl("/otherPage/lottery/roulette?cid=" + id)

			} else if (item.actTpl == 'blindBox') {
				//盲盒
				common.toUrl("/otherPage/lottery/blindBox?cid=" + id)

			} else if (item.actTpl == 'twistedEgg') {
				//扭蛋
				common.toUrl("/otherPage/lottery/gashapon?cid=" + id)

			}
		}

	},

	toPath(url) {
		if (!store.state.vid) return store.commit('setHome', {
			showMode: true
		});
		common.toUrl(url)
	},
	// 获取模版数据
	getBlockInfo(id, other = {}) {
		return new Promise((resolve, reject) => {
			$http.get({
				url: '/newdiy/api/v1/diy/getBlockInfo',
				data: {
					id,
					front: 1,
					...other
				}
			}).then(res => {
				if (res.status != 200) return pop.Toast(res.msg);
				const result = res.data;
				resolve(result)
			})
		})
	},

	// 去搜索
	toSearch() {
		common.toUrl('/pages/classify/search')
	},

	// 去文章详情
	artDetails(website_article_id) {
		common.toUrl(`/otherPage/article/artDetail?artId=${website_article_id}`)
	},

	// 跳tabbar
	/*
	   我的： /pages/user/user 2
	   分类： /pages/classify/classify 3
	   分类点餐：/pages/classify/repast 4
	   门店： /pages/store/storeList 5
	   预约列表： /pages/reserve/reserve 6
	   购物车: /pages/cart/cart 7
	   资讯: /pages/artList/artList 9
	   游戏: /pages/gameList/gameList 11
	*/

	toTab(tabId) {
		const tabars = store.state.tabBar.list;
		const isFlag = tabars.some((n) => n.id == tabId);
		let Url;
		if (tabId == 3) Url = '/pages/classify/classify';
		if (tabId == 4) Url = '/pages/classify/repast';
		if (tabId == 5) Url = '/pages/store/storeList';
		if (tabId == 6) Url = '/pages/reserve/reserve';
		if (tabId == 7) Url = '/pages/cart/cart';
		if (tabId == 8) Url = '/pages/artList/artList';
		if (tabId == 11) Url = '/pages/gameList/gameList';

		if (!isFlag) return common.rectTo(Url);
		store.commit('changeTab', {
			tabId
		});
		common.rectTo(Url);
	},
	chooseAddress() {
		return new Promise((resolve, reject) => {
			uni.chooseAddress({
				success(res) {
					resolve(res);
				},
				fail(err) {
					reject(err)
				}
			})
		})
	},

	hidePhone(phoneNumber) {
		if (!phoneNumber) return;
		return phoneNumber.replace(/(\d{3})\d{4}(\d{4})/, '$1 **** $2');
	},
	toCourses(goods_id) {
		common.toUrl(`/answer/play?goods_id=${goods_id}`)
	},
	// 记录播放时间
	saveChap(chapter_id, chapter_play_time) {
		$http.post({
			url: '/goodsLessonsApi/saveChapterLog',
			data: {
				chapter_id,
				chapter_play_time
			}
		}).then(res => {
			if (res.code != '200') return;
		})
	},
	format(item) {
		let time = parseInt(item);
		let min = Math.floor(time / 60) >= 10 ? Math.floor(time / 60) : `0${Math.floor(time / 60)}`;
		let sec = Math.floor(time % 60) >= 10 ? Math.floor(time % 60) : `0${Math.floor(time % 60)}`;
		return `${min}:${sec}`
	},

	getLocation() {
		return new Promise((resolve, reject) => {
			// #ifdef MP-WEIXIN
			wx.getFuzzyLocation({
				type: 'wgs84',
				success(res) {
					store.commit('Position', res)
					resolve(res);
				},
				fail(err) {
					console.log(err, 'err');
				}
			})
			// #endif

		})

	},

	toPosition(url) {
		if (store.state.position.longitude == 0) {
			const obj = {
				latitude: 29.563707,
				longitude: 106.550483,
			}
			store.commit('Position', obj)
		}
		common.toUrl(url)
	},
	//  支付
	getPayment(item) {
		return new Promise((resolve, reject) => {
			uni.requestPayment({
				provider: 'wxpay',
				orderInfo: item,
				timeStamp: item.timeStamp,
				nonceStr: item.nonceStr,
				package: item.package,
				signType: item.signType,
				paySign: item.paySign,
				success: (res) => {
					resolve(res)
				},
				fail: (err) => {
					reject(err);
				}
			})
		})
	},


	formatDistance(meters) {
		if (meters < 1000) return meters + 'm';
		if (meters > 1000) return (meters / 1000).toFixed(1) + 'km';
	},


	getTxConfirm(order_id) {
		return new Promise((resolve, reject) => {
			pop.showLoading('');
			$http.get({
				url: '/DiyApi/getTxConfirm',
				data: {
					order_id
				}
			}).then(res => {
				pop.hideLoading();
				if (res.code != 200) return pop.Toast(res.msg);
				const result = res.data.order_state;
				resolve(result);
			})
		})
	},

	toLogin() {
		common.toUrl('/pages/Login/Login')
	},

	Timestamp(timestamp) {
		let date = new Date(timestamp);
		let year = date.getFullYear();
		let month = date.getMonth() + 1;
		month = month < 10 ? '0' + month : month;
		let formattedDate = year + '.' + month;
		return formattedDate
	}
}


export default pop